package com.kinghood.productcenter.service.product.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.kinghood.infrastructure.model.KingHoodExceptionUtil;
import com.kinghood.infrastructure.model.constant.CommonConstants;
import com.kinghood.infrastructure.util.base.IdGenUtil;
import com.kinghood.infrastructure.util.UserUtil;
import com.kinghood.productcenter.common.model.constants.ProductConstant;
import com.kinghood.productcenter.common.model.dao.product.ProductAttributeDO;
import com.kinghood.productcenter.common.model.dao.product.ProductSkuBaseDO;
import com.kinghood.productcenter.common.model.dao.product.ProductSkuExtrasBaseDO;
import com.kinghood.productcenter.common.model.dto.product.ProductSkuExtrasReqDTO;
import com.kinghood.productcenter.common.model.vo.base.BaseAttributeVO;
import com.kinghood.productcenter.dao.product.ProductSkuExtrasBaseMapper;
import com.kinghood.productcenter.service.product.IProductAttributeService;
import com.kinghood.productcenter.service.product.IProductSkuExtrasBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinghood.productcenter.service.product.handler.ProductBaseHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@RequiredArgsConstructor
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class ProductSkuExtrasBaseServiceImpl extends ServiceImpl<ProductSkuExtrasBaseMapper, ProductSkuExtrasBaseDO> implements IProductSkuExtrasBaseService {

    private final IProductAttributeService productAttributeService;

    @Override
    public void addSkuExtras(List<ProductSkuExtrasReqDTO> skuExtrasList, Long productId, Map<String, ProductSkuBaseDO> skuMap, Map<String, BaseAttributeVO> attributeVOMap, Map<String, Long> oldExtrasMap) {

        if(CollectionUtils.isEmpty(skuExtrasList)){
            return ;
        }

        List<ProductSkuExtrasBaseDO> list = new ArrayList<>();
        List<ProductAttributeDO> attributeList = new ArrayList<>();

        skuExtrasList.forEach(x -> {
            ProductSkuBaseDO sku = skuMap.get(x.getSkuCode());
            KingHoodExceptionUtil.isNull(sku,"添加附件：sku编码异常");

            ProductSkuExtrasBaseDO one = new ProductSkuExtrasBaseDO();
            Long id = oldExtrasMap.get("" + sku.getProductId() + "-" + sku.getId());
            if (Objects.isNull(id)) {
                id = IdGenUtil.getId();
            }
            one.setId(id);
            one.setProductId(productId);
            one.setProductSkuId(sku.getId());
            one.setCreateTime(LocalDateTime.now());
            one.setUpdateTime(LocalDateTime.now());
            one.setCreateUserId(UserUtil.getUserId());
            list.add(one);

            if (CollectionUtils.isEmpty(x.getAttributes())) {
                return;
            }
            x.getAttributes().forEach((k, y) -> {
                if(ProductConstant.NO_ATTRIBUTE_LIST.contains(k)){
                    return;
                }
                BaseAttributeVO baseAttributeVO = attributeVOMap.get(k);
                KingHoodExceptionUtil.isNull(baseAttributeVO, "属性" + k + "不存在");

                ProductAttributeDO productAttributeDO = new ProductAttributeDO();
                productAttributeDO.setId(IdGenUtil.getId());
                productAttributeDO.setProductId(productId);
                productAttributeDO.setBusinessId(one.getId());
                productAttributeDO.setBusinessType(ProductAttributeDO.BUSINESS_TYPE_EXTRAS);
                productAttributeDO.setAttributeId(baseAttributeVO.getId());
                productAttributeDO.setAttributeCode(baseAttributeVO.getAttributeCode());
                productAttributeDO.setValue(ProductBaseHandler.handleAttributeValue(y));
                productAttributeDO.setValueFind(ProductBaseHandler.handleAttributeValueFind(productAttributeDO.getValue()));
                productAttributeDO.setValueType(baseAttributeVO.getValueType());
                productAttributeDO.setCreateTime(LocalDateTime.now());
                productAttributeDO.setCreateTime(LocalDateTime.now());
                productAttributeDO.setCreateUserId(UserUtil.getUserId());
                attributeList.add(productAttributeDO);
            });
        });

        this.saveBatch(list);
        productAttributeService.saveBatch(attributeList);

    }

    @Override
    public void deleteByProductId(Long productId, List<Long> idList) {

        new LambdaUpdateChainWrapper<>(this.getBaseMapper())
                .eq(ProductSkuExtrasBaseDO::getProductId,productId)
                .in(!CollectionUtils.isEmpty(idList),ProductSkuExtrasBaseDO::getId, idList)
                .eq(ProductSkuExtrasBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .remove();
    }

    @Override
    public Map<String, Long> getExtrasByProductId(Long id) {

        List<ProductSkuExtrasBaseDO> list = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .eq(ProductSkuExtrasBaseDO::getProductId, id)
                .eq(ProductSkuExtrasBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .list();

        Map<String, Long> idMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(list)) {
            idMap = list.stream()
                    .collect(Collectors.toMap(x -> "" + x.getProductId() + "-" + x.getProductSkuId(), ProductSkuExtrasBaseDO::getId, (k1, k2) -> k1));
        }
        return idMap;
    }
}

